package com.intretech.tj.studio;

import com.intretech.tj.global.parent.TriggerParent;
import com.intretech.tj.global.parent.VerticleParent;
import com.intretech.tj.mqtt.MQTTHandler;
import com.intretech.tj.mqtt.MQTTVerticle;
import com.intretech.tj.mqtt.OutLog;
import com.intretech.tj.mqtt.trigger.TopicNewTrigger;
import io.vertx.core.Promise;
import jakarta.enterprise.context.ApplicationScoped;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.intretech.tj.global.parent.OutLogParent.ServerStart;
import static com.intretech.tj.global.tools.JSONTool.toJSONString;

@Slf4j
@ApplicationScoped
public class StudioVerticle extends VerticleParent {

    private final OutLog outLog;

    private final MQTTVerticle mqttVerticle;

    private final MQTTHandler mqttHandler;

    private final TopicNewTrigger topicNewTrigger;

    Map<String, String> preinstall = new HashMap<>();

    public StudioVerticle(OutLog outLog, MQTTVerticle mqttVerticle, MQTTHandler mqttHandler, TopicNewTrigger topicNewTrigger) {
        this.outLog = outLog;
        this.mqttVerticle = mqttVerticle;
        this.mqttHandler = mqttHandler;
        this.topicNewTrigger = topicNewTrigger;
    }

    // 下方循环不考虑越界，故items数组的内容必须成对
    private final String[] items = new String[]{
            "cmd_vel", "geometry_msgs/msg/Twist",
            "current_pose", "geometry_msgs/msg/PoseStamped",
            "rfid_data", "std_msgs/msg/String",
            "scan", "sensor_msgs/msg/LaserScan",
            "pointcloud", "sensor_msgs/msg/PointCloud",
            "pointcloud2", "sensor_msgs/msg/PointCloud2",
            "imu", "sensor_msgs/msg/Imu",
    };
    private final String other = "std_msgs/msg/String";

    private final String topic = "topic/all";

    @Override
    public void start(Promise<Void> startPromise) {
        for (int i = 0; i < items.length; i++) {
            preinstall.put(items[i], items[++i]);
        }
        topicNewTrigger.setTrigger(TriggerParent.ALL, outLog.getServerName(), (newTopic) -> {
            List<TopicInfo> topicInfos = new ArrayList<>();
            mqttHandler.getTopicList().forEach(topic ->
                    topicInfos.add(new TopicInfo(topic, preinstall.getOrDefault(topic, other)))
            );
            mqttVerticle.retain(topic, 0, toJSONString(topicInfos));
        });
        log.info(outLog.getMessage(ServerStart));
    }
}
